aboutsummaryrefslogtreecommitdiff
path: root/pages/api/v2/episode/[id].js
blob: c1fac8bf316993d2d45f592a1e7a8781a85be2d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import axios from "axios";
import { rateLimitStrict, rateLimiterRedis, redis } from "@/lib/redis";
import appendImagesToEpisodes from "@/utils/combineImages";
import appendMetaToEpisodes from "@/utils/appendMetaToEpisodes";

const CONSUMET_URI = process.env.API_URI;
const API_KEY = process.env.API_KEY;

const isAscending = (data) => {
  for (let i = 1; i < data.length; i++) {
    if (data[i].number < data[i - 1].number) {
      return false;
    }
  }
  return true;
};

async function fetchConsumet(id, dub) {
  try {
    if (dub) {
      return [];
    }

    const { data } = await axios.get(
      `${CONSUMET_URI}/meta/anilist/episodes/${id}`
    );

    if (data?.message === "Anime not found" && data?.length < 1) {
      return [];
    }

    const reformatted = data.map((item) => ({
      id: item?.id || null,
      title: item?.title || null,
      img: item?.image || null,
      number: item?.number || null,
      createdAt: item?.createdAt || null,
      description: item?.description || null,
      url: item?.url || null,
    }));

    const array = [
      {
        map: true,
        providerId: "gogoanime",
        episodes: isAscending(reformatted)
          ? reformatted
          : reformatted.reverse(),
      },
    ];

    return array;
  } catch (error) {
    console.error("Error fetching and processing data:", error.message);
    return [];
  }
}

async function fetchAnify(id) {
  try {
    if (!process.env.API_KEY) {
      return [];
    }

    const { data } = await axios.get(
      `https://api.anify.tv/episodes/${id}?apikey=${API_KEY}`
    );

    if (!data) {
      return [];
    }

    const filtered = data.filter(
      (item) => item.providerId !== "animepahe" && item.providerId !== "kass"
    );

    return filtered;
  } catch (error) {
    console.error("Error fetching and processing data:", error.message);
    return [];
  }
}

async function fetchCoverImage(id) {
  try {
    if (!process.env.API_KEY) {
      return [];
    }

    const { data } = await axios.get(
      `https://api.anify.tv/content-metadata/${id}?apikey=${API_KEY}`
    );

    if (!data) {
      return [];
    }

    return data;
  } catch (error) {
    console.error("Error fetching and processing data:", error.message);
    return [];
  }
}

export default async function handler(req, res) {
  const { id, releasing = "false", dub = false, refresh = null } = req.query;

  // if releasing is true then cache for 10 minutes, if it false cache for 1 month;
  const cacheTime = releasing === "true" ? 60 * 10 : 60 * 60 * 24 * 30;

  let cached;
  let meta;

  if (redis) {
    try {
      const ipAddress = req.socket.remoteAddress;
      refresh
        ? await rateLimitStrict.consume(ipAddress)
        : await rateLimiterRedis.consume(ipAddress);
    } catch (error) {
      return res.status(429).json({
        error: `Too Many Requests, retry after ${error.msBeforeNext / 1000}`,
      });
    }

    if (refresh) {
      await redis.del(id);
      console.log("deleted cache");
    } else {
      cached = await redis.get(id);
      console.log("using redis");
    }

    meta = await redis.get(`meta:${id}`);
  }

  if (cached && !refresh) {
    if (dub) {
      const filtered = JSON.parse(cached).filter((item) =>
        item.episodes.some((epi) => epi.hasDub === true)
      );
      return res.status(200).json(filtered);
    } else {
      return res.status(200).json(JSON.parse(cached));
    }
  } else {
    const [consumet, anify, cover] = await Promise.all([
      fetchConsumet(id, dub),
      fetchAnify(id),
      fetchCoverImage(id),
    ]);

    const hasImage = consumet.map((i) =>
      i.episodes.some(
        (e) => e.img !== null || !e.img.includes("https://s4.anilist.co/")
      )
    );

    const rawData = [...consumet, ...(anify[0]?.data ?? [])];

    let data = rawData;

    if (meta) {
      data = await appendMetaToEpisodes(rawData, JSON.parse(meta));
    } else if (cover && cover?.length > 0 && !hasImage.includes(true))
      data = await appendImagesToEpisodes(rawData, cover);

    if (redis && cacheTime !== null) {
      await redis.set(
        id,
        JSON.stringify(data.filter((i) => i.episodes.length > 0)),
        "EX",
        cacheTime
      );
    }

    if (dub) {
      const filtered = data.filter((item) =>
        item.episodes.some((epi) => epi.hasDub === true)
      );
      return res.status(200).json(filtered);
    }

    console.log("fresh data");

    return res.status(200).json(data.filter((i) => i.episodes.length > 0));
  }
}